<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-title">用户管理</div>
      <el-button
        type="primary"
        @click="handleAdd"
        v-if="userStore.hasPermission('user.create')"
      >
        <el-icon><Plus /></el-icon>
        新增用户
      </el-button>
    </div>
    
    <div class="page-content">
      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :model="queryParams" inline>
          <el-form-item label="用户名">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input
              v-model="queryParams.email"
              placeholder="请输入邮箱"
              clearable
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="userList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" min-width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
              v-if="userStore.hasPermission('user.update')"
            >
              编辑
            </el-button>
            <el-button
              :type="row.status ? 'warning' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
              v-if="userStore.hasPermission('user.update')"
            >
              {{ row.status ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              v-if="userStore.hasPermission('user.delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSearch"
          @current-change="handleSearch"
        />
      </div>
    </div>
    
    <!-- 用户表单对话框 -->
    <UserForm
      v-model:visible="formVisible"
      :user="currentUser"
      @confirm="handleFormConfirm"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userApi } from '@/api/user'
import { useUserStore } from '@/stores/user'
import { formatDate } from '@/utils'
import UserForm from './UserForm.vue'

const userStore = useUserStore()

const loading = ref(false)
const userList = ref([])
const total = ref(0)
const selectedUsers = ref([])
const formVisible = ref(false)
const currentUser = ref(null)

const queryParams = reactive({
  page: 1,
  pageSize: 10,
  username: '',
  email: '',
  status: null
})

const loadUsers = async () => {
  try {
    loading.value = true
    const response = await userApi.getUsers(queryParams)
    userList.value = response.items || []
    total.value = response.total || 0
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  queryParams.page = 1
  loadUsers()
}

const handleReset = () => {
  Object.assign(queryParams, {
    page: 1,
    pageSize: 10,
    username: '',
    email: '',
    status: null
  })
  loadUsers()
}

const handleAdd = () => {
  currentUser.value = null
  formVisible.value = true
}

const handleEdit = (row) => {
  currentUser.value = { ...row }
  formVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 "${row.username}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await userApi.deleteUser(row.id)
    ElMessage.success('删除成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
    }
  }
}

const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status ? 0 : 1
    await userApi.toggleUserStatus(row.id, newStatus)
    ElMessage.success(`${newStatus ? '启用' : '禁用'}成功`)
    loadUsers()
  } catch (error) {
    console.error('状态切换失败:', error)
  }
}

const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

const handleFormConfirm = async (formData) => {
  try {
    if (currentUser.value?.id) {
      await userApi.updateUser(currentUser.value.id, formData)
      ElMessage.success('更新成功')
    } else {
      await userApi.createUser(formData)
      ElMessage.success('创建成功')
    }
    
    formVisible.value = false
    loadUsers()
  } catch (error) {
    console.error('保存用户失败:', error)
  }
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.page-container {
  background: #fff;
  border-radius: 4px;
  box-shadow: var(--box-shadow-base);
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  border-bottom: 1px solid var(--border-color-lighter);
}

.page-title {
  font-size: 18px;
  font-weight: 500;
  color: var(--text-color-primary);
}

.page-content {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
